# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : request_plugin.py
# Time       ：2023/10/27 13:43
# Author     ：YangYong
# version    ：python 3.10
# Description：
"""
from typing import Union

import requests
from pydantic import Field, BaseModel

from orderlines.libraries.BaseTask import BaseTask
from orderlines.utils.base_orderlines_type import BasePluginParam


class GetParam(BasePluginParam):
    url: str = Field(description='get请求url')
    params: Union[None, dict] = Field(description='get参数', default=None)
    headers: Union[None, dict] = Field(description='get请求头', default=None)


class PostParam(BasePluginParam):
    url: str = Field(description='post请求url')
    data: Union[None, dict] = Field(description='post参数', default=None)
    headers: Union[None, dict] = Field(description='post请求头', default=None)


class PutParam(BasePluginParam):
    url: str = Field(description='url请求url')
    data: Union[None, dict] = Field(description='put参数', default=None)
    headers: Union[None, dict] = Field(description='put请求头', default=None)


class DeleteParam(BasePluginParam):
    url: str = Field(description='url请求url')
    param: Union[None, dict] = Field(description='delete参数', default=None)
    headers: Union[None, dict] = Field(description='delete请求头', default=None)


class ResponseData(BaseModel):
    response_data: Union[str, dict] = Field(description='请求返回值')


class RequestPlugin(BaseTask):
    # 插件版本
    version = '1.0.0.1'
    # 插件名称
    title = 'http请求'

    def __init__(self):
        super(RequestPlugin, self).__init__()
        self.success_code = 200

    def _handle_response(self, res: requests.Response):
        """处理请求返回值，以下划线_开头的则不被读取到插件库中"""
        if res.status_code == self.success_code:
            return {'response_data': res.json()}
        else:
            return {'response_data': res.content}

    def get(self, param: GetParam) -> ResponseData:
        """
        获取请求
        第一行为插件方法的标题
        """
        res = requests.get(param.url, headers=param.headers, params=param.params)
        return self._handle_response(res)

    def post(self, param: PostParam) -> ResponseData:
        """创建请求"""
        res = requests.post(param.url, headers=param.headers, data=param.data)
        return self._handle_response(res)

    def put(self, param: PutParam) -> ResponseData:
        """修改请求"""
        res = requests.put(param.url, headers=param.headers, data=param.data)
        return self._handle_response(res)

    def delete(self, param: DeleteParam) -> ResponseData:
        """删除请求"""
        res = requests.delete(param.url, headers=param.headers, params=param.param)
        return self._handle_response(res)
